using System;
using System.Collections.Generic;
using System.Data;
using System.Windows.Forms;
using C1.Win.C1TrueDBGrid;
using PCSComMaterials.Inventory.BO;
using PCSComSale.Order.BO;
using PCSComSale.Order.DS;
using PCSComUtils.Common;
using PCSComUtils.Common.BO;
using PCSComUtils.PCSExc;
using PCSUtils.Log;
using PCSUtils.Utils;
using CancelEventArgs = System.ComponentModel.CancelEventArgs;

namespace PCSSale.Order
{
    /// <summary>
    /// Summary description for ConfirmShipManagement.
    /// </summary>
    public partial class ConfirmShipManagement : Form
    {
        public const string THIS = "PCSSale.Order.ConfirmShipManagement";
        
        private DataTable dtbGridLayOut;
        private DataSet dstData;
        private EnumAction mFormMode;
        private SOConfirmShipManagementBO boConfirm = new SOConfirmShipManagementBO();
        private SOReleaseOrderBO boRelease = new SOReleaseOrderBO();
        private UtilsBO boUtils = new UtilsBO();
        const string PARTY_CODE = "PARTY_CODE";
        const string PARTY_NAME = "PARTY_NAME";
        const string PARTY_ADD = "PARTY_ADD";
        const string COMMITTEDQTY_FLD = "CommittedQuantity";

        public ConfirmShipManagement()
        {
            //
            // Required for Windows Form Designer support
            //
            InitializeComponent();
        }

        #region private methods

        private void SwitchFormMode()
        {
            switch (mFormMode)
            {
                case EnumAction.Add:
                    dtmTransDate.Enabled = true;
                    txtTransNo.Enabled = btnTransNo.Enabled = false;
                    txtCommitNo.Enabled = btnCommitNo.Enabled = true;
                    txtComment.Enabled = true;

                    btnAdd.Enabled = false;
                    btnSave.Enabled = true;
                    btnDelete.Enabled = false;
                    btnPrint.Enabled = false;
                    break;
                case EnumAction.Edit:
                    dtmTransDate.Enabled = true;
                    txtTransNo.Enabled = btnTransNo.Enabled = false;
                    txtCommitNo.Enabled = btnCommitNo.Enabled = false;
                    txtComment.Enabled = true;
                    
                    btnAdd.Enabled = false;
                    btnDelete.Enabled = false;
                    btnPrint.Enabled = false;
                    break;
                default:
                    dtmTransDate.Enabled = false;
                    txtTransNo.Enabled = btnTransNo.Enabled = true;
                    txtCommitNo.Enabled = btnCommitNo.Enabled = false;
                    txtComment.Enabled = false;

                    btnAdd.Enabled = true;
                    btnSave.Enabled = false;
                    if (txtTransNo.Tag != null)
                    {
                        btnDelete.Enabled = true;
                        btnPrint.Enabled = true;
                    }
                    else
                    {
                        btnDelete.Enabled = false;
                        btnPrint.Enabled = false;
                    }
                    break;
            }
        }
        private void ClearForm(bool blnIsMain)
        {
            if (blnIsMain)
            {
                dtmTransDate.Value = null;
                txtTransNo.Text = string.Empty;
                txtTransNo.Tag = null;
                txtComment.Text = string.Empty;
            }
            txtCommitNo.Text = string.Empty;
            txtCommitNo.Tag = null;
            btnCommitNo.Tag = null;
            lblCommitNo.Tag = null;
            txtCustomerCode.Tag = null;
            txtCustomerCode.Text = string.Empty;
            txtCustomerName.Text = string.Empty;
            txtAddress.Text = string.Empty;
            
            if (dstData.Tables.Count > 0)
            {
                dstData.Tables[0].Clear();
            }
        }
        private void LoadDataToGrid()
        {
            dgrdData.DataSource = dstData.Tables[0];
            FormControlComponents.RestoreGridLayout(dgrdData, dtbGridLayOut);

            foreach (C1DisplayColumn c1Col in dgrdData.Splits[0].DisplayColumns)
                c1Col.Locked = true;

            dgrdData.Columns[IV_BinCacheTable.OHQUANTITY_FLD].NumberFormat = Constants.DECIMAL_NUMBERFORMAT;
            dgrdData.Columns[COMMITTEDQTY_FLD].NumberFormat = Constants.DECIMAL_NUMBERFORMAT;
            dgrdData.Columns[SO_ConfirmShipDetailTable.INVOICEQTY_FLD].NumberFormat = Constants.DECIMAL_NUMBERFORMAT;
            dgrdData.Columns[SO_CommitInventoryDetailTable.COMMITQUANTITY_FLD].NumberFormat = Constants.DECIMAL_NUMBERFORMAT;
            dgrdData.Columns[SO_ConfirmShipDetailTable.PRICE_FLD].NumberFormat = Constants.DECIMAL_NUMBERFORMAT;
            dgrdData.Columns[SO_SaleOrderDetailTable.VATPERCENT_FLD].NumberFormat = Constants.DECIMAL_NUMBERFORMAT;
            dgrdData.Columns[SO_SaleOrderDetailTable.VATAMOUNT_FLD].NumberFormat = Constants.DECIMAL_NUMBERFORMAT;

            SwitchFormMode();
        }
        private void FillCommitData(int pintCommitMasterID)
        {
            if (pintCommitMasterID > 0)
            {
                DataRow drowMasterInfo = boRelease.GetMasterVO(pintCommitMasterID);
                txtCommitNo.Text = drowMasterInfo[SO_CommitInventoryMasterTable.COMMITMENTNO_FLD].ToString();
                txtCommitNo.Tag = pintCommitMasterID;
                btnCommitNo.Tag = drowMasterInfo[SO_CommitInventoryMasterTable.SALEORDERMASTERID_FLD];
                DataRow drowSaleInfo = boRelease.GetSOMasterVO(Convert.ToInt32(btnCommitNo.Tag));
                lblCommitNo.Tag = drowSaleInfo[SO_SaleOrderMasterTable.CURRENCYID_FLD];
                txtCustomerCode.Tag = drowSaleInfo[SO_SaleOrderMasterTable.EXCHANGERATE_FLD];
                txtCustomerCode.Text = drowMasterInfo[PARTY_CODE].ToString();
                txtCustomerName.Text = drowMasterInfo[PARTY_NAME].ToString();
                txtAddress.Text = drowMasterInfo[PARTY_ADD].ToString();
                txtAddress.Tag = drowMasterInfo[SO_CommitInventoryDetailTable.MASTERLOCATIONID_FLD];

                //load default data for grid
                DataSet dstTemp = boConfirm.ListConfirmable(pintCommitMasterID);
                dstData.Tables[0].Clear();
                int i = 0;
                foreach (DataRow dr in dstTemp.Tables[0].Rows)
                {
                    i++;
                    DataRow drNew = dstData.Tables[0].NewRow();
                    foreach (DataColumn dcol in dstData.Tables[0].Columns)
                    {
                        drNew[dcol.ColumnName] = dr[dcol.ColumnName];
                    }
                    drNew[SO_CommitInventoryDetailTable.LINE_FLD] = i;
                    dstData.Tables[0].Rows.Add(drNew);
                }
                LoadDataToGrid();
            }
        }
        private bool ValidateData()
        {
            #region check mandatory

            if (dtmTransDate.Value == DBNull.Value)
            {
                PCSMessageBox.Show(ErrorCode.MANDATORY_INVALID, MessageBoxIcon.Warning);
                dtmTransDate.Focus();
                return false;
            }
            if (txtTransNo.Text.Trim().Length == 0)
            {
                PCSMessageBox.Show(ErrorCode.MANDATORY_INVALID, MessageBoxIcon.Warning);
                txtTransNo.Focus();
                return false;
            }
            if (txtCommitNo.Text.Trim().Length == 0)
            {
                PCSMessageBox.Show(ErrorCode.MANDATORY_INVALID, MessageBoxIcon.Warning);
                txtCommitNo.Focus();
                return false;
            }

            #endregion

            #region check grid
            for (int i = 0; i < dgrdData.RowCount - 1; i++)
            {
                try
                {
                    decimal decCommitQuantity = Convert.ToDecimal(dgrdData[i, SO_ConfirmShipDetailTable.INVOICEQTY_FLD]);
                    decimal decAvailableQuantity = 0;
                    try
                    {
                        decAvailableQuantity = Convert.ToDecimal(Convert.ToDecimal(dgrdData[i, IV_BinCacheTable.OHQUANTITY_FLD]));
                    }
                    catch { }
                    if (decCommitQuantity > decAvailableQuantity)
                    {
                        PCSMessageBox.Show(ErrorCode.MESSAGE_AVAILABLE_QTY_MUST_GREATER_THAN_ZERO, MessageBoxIcon.Warning);
                        dgrdData.Row = i;
                        dgrdData.Col = dgrdData.Splits[0].DisplayColumns.IndexOf(dgrdData.Splits[0].DisplayColumns[SO_CommitInventoryDetailTable.COMMITQUANTITY_FLD]);
                        dgrdData.Focus();
                        return false;
                    }
                }
                catch
                {
                    PCSMessageBox.Show(ErrorCode.MESSAGE_INVALID_NUMERIC, MessageBoxIcon.Error);
                    dgrdData.Row = i;
                    dgrdData.Col = dgrdData.Splits[0].DisplayColumns.IndexOf(dgrdData.Splits[0].DisplayColumns[SO_CommitInventoryDetailTable.COMMITQUANTITY_FLD]);
                    dgrdData.Focus();
                    return false;
                }
            }
            #endregion

            return true;
        }
        private void LoadDataFromMaster(int pintMasterID)
        {
            DataRow drowMasterInfo = boConfirm.GetMasterVO(pintMasterID);
            dtmTransDate.Value = Convert.ToDateTime(drowMasterInfo[SO_ConfirmShipMasterTable.SHIPPEDDATE_FLD]);
            txtTransNo.Text = drowMasterInfo[SO_ConfirmShipMasterTable.CONFIRMSHIPNO_FLD].ToString();
            txtTransNo.Tag = drowMasterInfo[SO_ConfirmShipMasterTable.CONFIRMSHIPMASTERID_FLD];
            txtCommitNo.Text = drowMasterInfo[SO_CommitInventoryMasterTable.COMMITMENTNO_FLD].ToString();
            txtCommitNo.Tag = drowMasterInfo[SO_CommitInventoryMasterTable.COMMITINVENTORYMASTERID_FLD];
            btnCommitNo.Tag = drowMasterInfo[SO_ConfirmShipMasterTable.SALEORDERMASTERID_FLD];
            txtCustomerCode.Text = drowMasterInfo[PARTY_CODE].ToString();
            txtCustomerName.Text = drowMasterInfo[PARTY_NAME].ToString();
            txtAddress.Text = drowMasterInfo[PARTY_ADD].ToString();
            txtAddress.Tag = drowMasterInfo[SO_ConfirmShipMasterTable.MASTERLOCATIONID_FLD].ToString();
            txtComment.Text = drowMasterInfo[SO_ConfirmShipMasterTable.COMMENT_FLD].ToString();
            dstData = boConfirm.ListByMaster(pintMasterID);
            int i = 0;
            foreach (DataRow dr in dstData.Tables[0].Rows)
            {
                i++;
                dr[SO_CommitInventoryDetailTable.LINE_FLD] = i;
            }
            LoadDataToGrid();
        }
        private int UpdateConfirmShipment(SO_ConfirmShipMasterVO pvoMaster, DataSet pdstData)
        {
            InventoryUtilsBO boIVUtils = new InventoryUtilsBO();
            SaleOrderBO boSaleOrder = new SaleOrderBO();
            DataSet dtbBinCache = boIVUtils.ListAllBinCache();
            DataSet dtbLocCache = boIVUtils.ListAllLocationCache();
            DataSet dtbMasLocCache = boIVUtils.ListAllMasLocCache();
            // get transaction history table schema
            int intTranTypeID = boUtils.GetTransTypeIDByCode(TransactionTypeEnum.ShippingManagement.ToString());
            DataSet dtbTransaction = boIVUtils.ListTransactionHistory(pvoMaster.ConfirmShipMasterID, intTranTypeID);
            int intNewTranTypeID = boUtils.GetTransTypeIDByCode(TransactionTypeEnum.DeleteTransaction.ToString());

            DataSet dstCSDetail = pdstData.Clone();
            DataSet dstSODetail = boSaleOrder.ListSaleOrderDetail(pvoMaster.SaleOrderMasterID);
            var completedSaleOrderDetails = new List<int>();

            DateTime dtmServerDate = new UtilsBO().GetDBDate();
            DataSet dtbCommit = boConfirm.ListCommit();

            if (mFormMode == EnumAction.Add)
            {
                #region Add confirmship

                pvoMaster.ConfirmShipMasterID = -1;

                foreach (DataRow dr in pdstData.Tables[0].Rows)
                {
                    if (dr.RowState == DataRowState.Deleted)
                    {
                        continue;
                    }

                    var saleOrderDetailId = Convert.ToInt32(dr[SO_SaleOrderDetailTable.SALEORDERDETAILID_FLD]);
                    DataRow drDetail = dstCSDetail.Tables[SO_ConfirmShipDetailTable.TABLE_NAME].NewRow();
                    drDetail[SO_ConfirmShipDetailTable.CONFIRMSHIPMASTERID_FLD] = pvoMaster.ConfirmShipMasterID;
                    drDetail[SO_ConfirmShipDetailTable.DELIVERYSCHEDULEID_FLD] = dr[SO_DeliveryScheduleTable.DELIVERYSCHEDULEID_FLD];
                    drDetail[SO_ConfirmShipDetailTable.PRODUCTID_FLD] = dr[ITM_ProductTable.PRODUCTID_FLD];
                    drDetail[SO_ConfirmShipDetailTable.SALEORDERDETAILID_FLD] = saleOrderDetailId;
                    drDetail[SO_ConfirmShipDetailTable.PRICE_FLD] = dr[SO_ConfirmShipDetailTable.PRICE_FLD];
                    drDetail[SO_ConfirmShipDetailTable.INVOICEQTY_FLD] = dr[SO_ConfirmShipDetailTable.INVOICEQTY_FLD];
                    drDetail[SO_ConfirmShipDetailTable.VATAMOUNT_FLD] = dr[SO_ConfirmShipDetailTable.VATAMOUNT_FLD];
                    drDetail[SO_ConfirmShipDetailTable.VATPERCENT_FLD] = dr[SO_ConfirmShipDetailTable.VATPERCENT_FLD];
                    drDetail[SO_ConfirmShipDetailTable.VATPERCENT_FLD] = dr[SO_ConfirmShipDetailTable.VATPERCENT_FLD];
                    drDetail[SO_ConfirmShipDetailTable.OHQuantity] = dr[SO_ConfirmShipDetailTable.OHQuantity];
                    drDetail[SO_ConfirmShipDetailTable.CommittedQuantity] = dr[SO_ConfirmShipDetailTable.CommittedQuantity];
                    
                    dstCSDetail.Tables[SO_ConfirmShipDetailTable.TABLE_NAME].Rows.Add(drDetail);

                    //update commit inventory detail
                    int intDeliveryID = Convert.ToInt32(dr[SO_DeliveryScheduleTable.DELIVERYSCHEDULEID_FLD]);
                    DataRow[] drowCommits = dtbCommit.Tables[0].Select(SO_DeliveryScheduleTable.DELIVERYSCHEDULEID_FLD + "=" + intDeliveryID);
                    decimal decQty = decimal.Parse(dr[SO_ConfirmShipDetailTable.INVOICEQTY_FLD].ToString());
                    foreach (DataRow drowCommit in drowCommits)
                    {
                        #region prepare

                        drowCommit[SO_CommitInventoryDetailTable.SHIPPED_FLD] = true;
                        drowCommit[SO_CommitInventoryDetailTable.SHIPDATE_FLD] = pvoMaster.ShippedDate;
                        int intMasLocID = pvoMaster.MasterLocationID;
                        int intLocID = 0;
                        try
                        {
                            intLocID = int.Parse(drowCommit[SO_CommitInventoryDetailTable.LOCATIONID_FLD].ToString());
                        }
                        catch { }

                        int intBinID = 0;
                        try
                        {
                            intBinID = int.Parse(drowCommit[SO_CommitInventoryDetailTable.BINID_FLD].ToString());
                        }
                        catch { }

                        int intProductID = int.Parse(dr[ITM_ProductTable.PRODUCTID_FLD].ToString());

                        int intStockUMID = Convert.ToInt32(drowCommit[SO_CommitInventoryDetailTable.STOCKUMID_FLD]);
                        #endregion

                        #region Cache

                        string strFilter = IV_BinCacheTable.MASTERLOCATIONID_FLD + "=" + intMasLocID
                            + " AND " + IV_BinCacheTable.LOCATIONID_FLD + "=" + intLocID
                            + " AND " + IV_BinCacheTable.BINID_FLD + "=" + intBinID
                            + " AND " + IV_BinCacheTable.PRODUCTID_FLD + "=" + intProductID;
                        string strLocFilter = IV_BinCacheTable.MASTERLOCATIONID_FLD + "=" + intMasLocID
                            + " AND " + IV_BinCacheTable.LOCATIONID_FLD + "=" + intLocID
                            + " AND " + IV_BinCacheTable.PRODUCTID_FLD + "=" + intProductID;
                        string strMasLocFilter = IV_BinCacheTable.MASTERLOCATIONID_FLD + "=" + intMasLocID
                            + " AND " + IV_BinCacheTable.PRODUCTID_FLD + "=" + intProductID;

                        DataRow[] drowBinCache = dtbBinCache.Tables[0].Select(strFilter);
                        DataRow[] drowLocCache = dtbLocCache.Tables[0].Select(strLocFilter);
                        DataRow[] drowMasLocCache = dtbMasLocCache.Tables[0].Select(strMasLocFilter);

                        #region subtract commit

                        decimal decBinCommit = 0, decLocCommit = 0, decMasLocCommit = 0;
                        try
                        {
                            decBinCommit = Convert.ToDecimal(drowBinCache[0][IV_BinCacheTable.COMMITQUANTITY_FLD]);
                        }
                        catch { }
                        try
                        {
                            decLocCommit = Convert.ToDecimal(drowLocCache[0][IV_LocationCacheTable.COMMITQUANTITY_FLD]);
                        }
                        catch { }
                        try
                        {
                            decMasLocCommit = Convert.ToDecimal(drowMasLocCache[0][IV_MasLocCacheTable.COMMITQUANTITY_FLD]);
                        }
                        catch { }
                        drowBinCache[0][IV_BinCacheTable.COMMITQUANTITY_FLD] = decBinCommit - decQty;
                        drowLocCache[0][IV_LocationCacheTable.COMMITQUANTITY_FLD] = decLocCommit - decQty;
                        drowMasLocCache[0][IV_MasLocCacheTable.COMMITQUANTITY_FLD] = decMasLocCommit - decQty;

                        #endregion

                        #region substract onhand

                        decimal decBinOH = 0, decLocOH = 0, decMasLocOH = 0;
                        try
                        {
                            decBinOH = Convert.ToDecimal(drowBinCache[0][IV_BinCacheTable.OHQUANTITY_FLD]);
                        }
                        catch { }
                        try
                        {
                            decLocOH = Convert.ToDecimal(drowLocCache[0][IV_LocationCacheTable.OHQUANTITY_FLD]);
                        }
                        catch { }
                        try
                        {
                            decMasLocOH = Convert.ToDecimal(drowMasLocCache[0][IV_MasLocCacheTable.OHQUANTITY_FLD]);
                        }
                        catch { }
                        drowBinCache[0][IV_BinCacheTable.OHQUANTITY_FLD] = decBinOH - decQty;
                        drowLocCache[0][IV_LocationCacheTable.OHQUANTITY_FLD] = decLocOH - decQty;
                        drowMasLocCache[0][IV_MasLocCacheTable.OHQUANTITY_FLD] = decMasLocOH - decQty;

                        #endregion

                        #endregion

                        #region Transaction history
                        //SaveTransactionHistory
                        DataRow drowTransaction = dtbTransaction.Tables[0].NewRow();
                        drowTransaction[MST_TransactionHistoryTable.CCNID_FLD] = pvoMaster.CCNID;
                        drowTransaction[MST_TransactionHistoryTable.TRANSDATE_FLD] = dtmServerDate;
                        drowTransaction[MST_TransactionHistoryTable.POSTDATE_FLD] = (DateTime)drowCommit[SO_CommitInventoryDetailTable.SHIPDATE_FLD];
                        drowTransaction[MST_TransactionHistoryTable.REFMASTERID_FLD] = pvoMaster.ConfirmShipMasterID;
                        drowTransaction[MST_TransactionHistoryTable.PRODUCTID_FLD] = intProductID;
                        drowTransaction[MST_TransactionHistoryTable.TRANTYPEID_FLD] = intTranTypeID;
                        drowTransaction[MST_TransactionHistoryTable.USERNAME_FLD] = SystemProperty.UserName;
                        drowTransaction[MST_TransactionHistoryTable.QUANTITY_FLD] = decQty;
                        drowTransaction[MST_TransactionHistoryTable.MASTERLOCATIONID_FLD] = intMasLocID;
                        drowTransaction[MST_TransactionHistoryTable.MASLOCOHQUANTITY_FLD] = decMasLocOH;
                        drowTransaction[MST_TransactionHistoryTable.MASLOCCOMMITQUANTITY_FLD] = decMasLocCommit;
                        drowTransaction[MST_TransactionHistoryTable.LOCATIONID_FLD] = intLocID;
                        drowTransaction[MST_TransactionHistoryTable.LOCATIONOHQUANTITY_FLD] = decLocOH;
                        drowTransaction[MST_TransactionHistoryTable.LOCATIONCOMMITQUANTITY_FLD] = decLocCommit;
                        drowTransaction[MST_TransactionHistoryTable.BINID_FLD] = intBinID;
                        drowTransaction[MST_TransactionHistoryTable.BINOHQUANTITY_FLD] = decBinOH;
                        drowTransaction[MST_TransactionHistoryTable.BINCOMMITQUANTITY_FLD] = decBinCommit;
                        drowTransaction[MST_TransactionHistoryTable.STOCKUMID_FLD] = intStockUMID;
                        dtbTransaction.Tables[0].Rows.Add(drowTransaction);
                        #endregion
                    }

                    //Update sale order detail
                    DataRow[] arrSODetail = dstSODetail.Tables[0].Select(SO_SaleOrderDetailTable.SALEORDERDETAILID_FLD + "=" + saleOrderDetailId);
                    if (arrSODetail.Length > 0)
                    {
                        decimal decOrderQuantity = Convert.ToDecimal(arrSODetail[0][SO_SaleOrderDetailTable.ORDERQUANTITY_FLD]);
                        decimal decShipQty = 0;
                        try
                        {
                            decShipQty = Convert.ToDecimal(arrSODetail[0][SO_SaleOrderDetailTable.SHIPQUANTITY_FLD]);
                        }
                        catch { }
                        arrSODetail[0][SO_SaleOrderDetailTable.SHIPQUANTITY_FLD] = decShipQty + decQty;
                        if (decOrderQuantity <= (decShipQty + decQty))
                        {
                            // add to completed list
                            completedSaleOrderDetails.Add(saleOrderDetailId);
                        }
                    }
                }

                pvoMaster.ConfirmShipMasterID = boConfirm.InsertConfirmShipment(pvoMaster, dstCSDetail, dtbCommit,
                    dtbMasLocCache, dtbLocCache, dtbBinCache, completedSaleOrderDetails, dtbTransaction, pdstData);
              
                #endregion
            }
            else if (mFormMode == EnumAction.Delete)
            {
                #region Delete confirmship

                foreach (DataRow dr in pdstData.Tables[0].Rows)
                {
                    if (dr.RowState == DataRowState.Deleted)
                        continue;

                    //update commit inventory detail
                    int intDeliveryID = Convert.ToInt32(dr[SO_DeliveryScheduleTable.DELIVERYSCHEDULEID_FLD]);
                    DataRow[] drowCommits = dtbCommit.Tables[0].Select(SO_DeliveryScheduleTable.DELIVERYSCHEDULEID_FLD + "=" + intDeliveryID);
                    decimal decQty = decimal.Parse(dr[SO_ConfirmShipDetailTable.INVOICEQTY_FLD].ToString());
                    foreach (DataRow drowCommit in drowCommits)
                    {
                        #region prepare

                        drowCommit[SO_CommitInventoryDetailTable.SHIPPED_FLD] = false;
                        drowCommit[SO_CommitInventoryDetailTable.SHIPDATE_FLD] = DBNull.Value;
                        int intMasLocID = pvoMaster.MasterLocationID;
                        int intLocID = 0;
                        try
                        {
                            intLocID = int.Parse(drowCommit[SO_CommitInventoryDetailTable.LOCATIONID_FLD].ToString());
                        }
                        catch { }

                        int intBinID = 0;
                        try
                        {
                            intBinID = int.Parse(drowCommit[SO_CommitInventoryDetailTable.BINID_FLD].ToString());
                        }
                        catch { }

                        int intProductID = int.Parse(dr[ITM_ProductTable.PRODUCTID_FLD].ToString());
                        #endregion

                        #region Cache

                        string strFilter = IV_BinCacheTable.MASTERLOCATIONID_FLD + "=" + intMasLocID
                            + " AND " + IV_BinCacheTable.LOCATIONID_FLD + "=" + intLocID
                            + " AND " + IV_BinCacheTable.BINID_FLD + "=" + intBinID
                            + " AND " + IV_BinCacheTable.PRODUCTID_FLD + "=" + intProductID;
                        string strLocFilter = IV_BinCacheTable.MASTERLOCATIONID_FLD + "=" + intMasLocID
                            + " AND " + IV_BinCacheTable.LOCATIONID_FLD + "=" + intLocID
                            + " AND " + IV_BinCacheTable.PRODUCTID_FLD + "=" + intProductID;
                        string strMasLocFilter = IV_BinCacheTable.MASTERLOCATIONID_FLD + "=" + intMasLocID
                            + " AND " + IV_BinCacheTable.PRODUCTID_FLD + "=" + intProductID;

                        DataRow[] drowBinCache = dtbBinCache.Tables[0].Select(strFilter);
                        DataRow[] drowLocCache = dtbLocCache.Tables[0].Select(strLocFilter);
                        DataRow[] drowMasLocCache = dtbMasLocCache.Tables[0].Select(strMasLocFilter);

                        #region add commit

                        decimal decBinCommit = 0, decLocCommit = 0, decMasLocCommit = 0;
                        try
                        {
                            decBinCommit = Convert.ToDecimal(drowBinCache[0][IV_BinCacheTable.COMMITQUANTITY_FLD]);
                        }
                        catch { }
                        try
                        {
                            decLocCommit = Convert.ToDecimal(drowLocCache[0][IV_LocationCacheTable.COMMITQUANTITY_FLD]);
                        }
                        catch { }
                        try
                        {
                            decMasLocCommit = Convert.ToDecimal(drowMasLocCache[0][IV_MasLocCacheTable.COMMITQUANTITY_FLD]);
                        }
                        catch { }
                        drowBinCache[0][IV_BinCacheTable.COMMITQUANTITY_FLD] = decBinCommit + decQty;
                        drowLocCache[0][IV_LocationCacheTable.COMMITQUANTITY_FLD] = decLocCommit + decQty;
                        drowMasLocCache[0][IV_MasLocCacheTable.COMMITQUANTITY_FLD] = decMasLocCommit + decQty;

                        #endregion

                        #region add onhand

                        decimal decBinOH = 0, decLocOH = 0, decMasLocOH = 0;
                        try
                        {
                            decBinOH = Convert.ToDecimal(drowBinCache[0][IV_BinCacheTable.OHQUANTITY_FLD]);
                        }
                        catch { }
                        try
                        {
                            decLocOH = Convert.ToDecimal(drowLocCache[0][IV_LocationCacheTable.OHQUANTITY_FLD]);
                        }
                        catch { }
                        try
                        {
                            decMasLocOH = Convert.ToDecimal(drowMasLocCache[0][IV_MasLocCacheTable.OHQUANTITY_FLD]);
                        }
                        catch { }
                        drowBinCache[0][IV_BinCacheTable.OHQUANTITY_FLD] = decBinOH + decQty;
                        drowLocCache[0][IV_LocationCacheTable.OHQUANTITY_FLD] = decLocOH + decQty;
                        drowMasLocCache[0][IV_MasLocCacheTable.OHQUANTITY_FLD] = decMasLocOH + decQty;

                        #endregion

                        #endregion
                    }

                    //Update sale order detail
                    DataRow[] arrSODetail = dstSODetail.Tables[0].Select(SO_SaleOrderDetailTable.SALEORDERDETAILID_FLD + "=" + int.Parse(dr[SO_SaleOrderDetailTable.SALEORDERDETAILID_FLD].ToString()));
                    if (arrSODetail.Length > 0)
                    {
                        decimal decShippedQty = 0;
                        try
                        {
                            decShippedQty = Convert.ToDecimal(arrSODetail[0][SO_SaleOrderDetailTable.SHIPQUANTITY_FLD]);
                        }
                        catch { }
                        arrSODetail[0][SO_SaleOrderDetailTable.SHIPQUANTITY_FLD] = decShippedQty - decQty;
                        arrSODetail[0][SO_SaleOrderDetailTable.SHIPCOMPLETED_FLD] = false;
                    }
                }

                boConfirm.DeleteConfirmShipment(pvoMaster.ConfirmShipMasterID, pvoMaster.SaleOrderMasterID, dstCSDetail, dtbCommit, dtbMasLocCache,
                    dtbLocCache, dtbBinCache, dstSODetail, intTranTypeID, intNewTranTypeID);

                #endregion
            }
            return pvoMaster.ConfirmShipMasterID;
        }
        
        #endregion

        private void ConfirmShipManagement_Load(object sender, EventArgs e)
        {
            const string METHOD_NAME = THIS + ".ConfirmShipManagement_Load()";
            try
            {
                Security objSecurity = new Security();
                this.Name = THIS;
                if (objSecurity.SetRightForUserOnForm(this, SystemProperty.UserName) == 0)
                {
                    this.Close();
                    PCSMessageBox.Show(ErrorCode.MESSAGE_YOU_HAVE_NO_RIGHT_TO_VIEW, MessageBoxIcon.Warning);
                    return;
                }

                //get grid layout
                dtbGridLayOut = FormControlComponents.StoreGridLayout(dgrdData);

                dstData = boConfirm.ListByMaster(0);
                LoadDataToGrid();

                mFormMode = EnumAction.Default;
                SwitchFormMode();
            }
            catch (PCSException ex)
            {
                PCSMessageBox.Show(ex.mCode, MessageBoxIcon.Error);
                try
                {
                    Logger.LogMessage(ex.CauseException, METHOD_NAME, Level.ERROR);
                }
                catch
                {
                    PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION);
                }
            }
            catch (Exception ex)
            {
                PCSMessageBox.Show(ErrorCode.OTHER_ERROR);
                try
                {
                    Logger.LogMessage(ex, METHOD_NAME, Level.ERROR);
                }
                catch
                {
                    PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION);
                }
            }
        }
        private void btnAdd_Click(object sender, EventArgs e)
        {
            const string METHOD_NAME = THIS + ".btnAdd_Click()";
            try
            {
                mFormMode = EnumAction.Add;
                ClearForm(true);
                dtmTransDate.Value = boUtils.GetDBDate();
                txtTransNo.Text = FormControlComponents.GetNoByMask(this);
                SwitchFormMode();
                txtCommitNo.Focus();
            }
            catch (PCSException ex)
            {
                PCSMessageBox.Show(ex.mCode, MessageBoxIcon.Error);
                try
                {
                    Logger.LogMessage(ex.CauseException, METHOD_NAME, Level.ERROR);
                }
                catch
                {
                    PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION);
                }
            }
            catch (Exception ex)
            {
                PCSMessageBox.Show(ErrorCode.OTHER_ERROR);
                try
                {
                    Logger.LogMessage(ex, METHOD_NAME, Level.ERROR);
                }
                catch
                {
                    PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION);
                }
            }
        }

        private void btnDelete_Click(object sender, EventArgs e)
        {
            const string METHOD_NAME = THIS + ".btnDelete_Click()";
            try
            {
                DialogResult dlgResult = PCSMessageBox.Show(ErrorCode.MESSAGE_DELETE_RECORD, MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1);
                if (dlgResult == DialogResult.Yes)
                {
                    mFormMode = EnumAction.Delete;
                    SO_ConfirmShipMasterVO voMaster = new SO_ConfirmShipMasterVO();
                    voMaster.ConfirmShipMasterID = Convert.ToInt32(txtTransNo.Tag);
                    voMaster.MasterLocationID = Convert.ToInt32(txtAddress.Tag);
                    voMaster.SaleOrderMasterID = Convert.ToInt32(btnCommitNo.Tag);
                    UpdateConfirmShipment(voMaster, dstData);

                    PCSMessageBox.Show(ErrorCode.MESSAGE_AFTER_SAVE_DATA);
                    mFormMode = EnumAction.Default;
                    ClearForm(true);
                    SwitchFormMode();
                }
            }
            catch (PCSException ex)
            {
                PCSMessageBox.Show(ex.mCode, MessageBoxIcon.Error);
                try
                {
                    Logger.LogMessage(ex.CauseException, METHOD_NAME, Level.ERROR);
                }
                catch
                {
                    PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION);
                }
            }
            catch (Exception ex)
            {
                PCSMessageBox.Show(ErrorCode.OTHER_ERROR);
                try
                {
                    Logger.LogMessage(ex, METHOD_NAME, Level.ERROR);
                }
                catch
                {
                    PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION);
                }
            }
        }

        private void btnPrint_Click(object sender, EventArgs e)
        {
            const string METHOD_NAME = THIS + ".btnPrint_Click()";
            try
            {

            }
            catch (PCSException ex)
            {
                PCSMessageBox.Show(ex.mCode, MessageBoxIcon.Error);
                try
                {
                    Logger.LogMessage(ex.CauseException, METHOD_NAME, Level.ERROR);
                }
                catch
                {
                    PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION);
                }
            }
            catch (Exception ex)
            {
                PCSMessageBox.Show(ErrorCode.OTHER_ERROR);
                try
                {
                    Logger.LogMessage(ex, METHOD_NAME, Level.ERROR);
                }
                catch
                {
                    PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION);
                }
            }
        }

        private void btnHelp_Click(object sender, EventArgs e)
        {
            const string METHOD_NAME = THIS + ".btnHelp_Click()";
            try
            {

            }
            catch (PCSException ex)
            {
                PCSMessageBox.Show(ex.mCode, MessageBoxIcon.Error);
                try
                {
                    Logger.LogMessage(ex.CauseException, METHOD_NAME, Level.ERROR);
                }
                catch
                {
                    PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION);
                }
            }
            catch (Exception ex)
            {
                PCSMessageBox.Show(ErrorCode.OTHER_ERROR);
                try
                {
                    Logger.LogMessage(ex, METHOD_NAME, Level.ERROR);
                }
                catch
                {
                    PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION);
                }
            }
        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            const string METHOD_NAME = THIS + ".btnClose_Click()";
            try
            {
                this.Close();
            }
            catch (PCSException ex)
            {
                PCSMessageBox.Show(ex.mCode, MessageBoxIcon.Error);
                try
                {
                    Logger.LogMessage(ex.CauseException, METHOD_NAME, Level.ERROR);
                }
                catch
                {
                    PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION);
                }
            }
            catch (Exception ex)
            {
                PCSMessageBox.Show(ErrorCode.OTHER_ERROR);
                try
                {
                    Logger.LogMessage(ex, METHOD_NAME, Level.ERROR);
                }
                catch
                {
                    PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION);
                }
            }
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            const string METHOD_NAME = THIS + ".btnSave_Click()";
            try
            {
                if (Security.IsDifferencePrefix(this, lblTransNo, txtTransNo))
                {
                    return;
                }
                if (!dgrdData.EditActive && ValidateData())
                {
                    dgrdData.UpdateData();

                    // synchronyze data
                    FormControlComponents.SynchronyGridData(dgrdData);
                    SO_ConfirmShipMasterVO voMaster = new SO_ConfirmShipMasterVO();
                    voMaster.CCNID = SystemProperty.CCNID;
                    voMaster.ConfirmShipNo = txtTransNo.Text;
                    DateTime dtmShippedDate = (DateTime)dtmTransDate.Value;
                    voMaster.ShippedDate = new DateTime(dtmShippedDate.Year, dtmShippedDate.Month, dtmShippedDate.Day);
                    voMaster.InvoiceDate = voMaster.ShippedDate;
                    voMaster.ShipCode = voMaster.ConfirmShipNo;
                    if (lblCommitNo.Tag != DBNull.Value)
                    {
                        voMaster.CurrencyID = Convert.ToInt32(lblCommitNo.Tag);
                    }
                    voMaster.ExchangeRate = Convert.ToDecimal(txtCustomerCode.Tag);
                    voMaster.SaleOrderMasterID = Convert.ToInt32(btnCommitNo.Tag);
                    voMaster.MasterLocationID = Convert.ToInt32(txtAddress.Tag);
                    voMaster.Username = SystemProperty.UserName;
                    voMaster.Comment = txtComment.Text.Trim();
                    voMaster.ConfirmShipMasterID = UpdateConfirmShipment(voMaster, dstData);
                    txtTransNo.Tag = voMaster.ConfirmShipMasterID;
                    PCSMessageBox.Show(ErrorCode.MESSAGE_AFTER_SAVE_DATA);
                    mFormMode = EnumAction.Default;
                    SwitchFormMode();
                    txtTransNo.Focus();
                }
            }
            catch (PCSException ex)
            {
                if (ex.mCode == ErrorCode.DUPLICATE_KEY)
                {
                    PCSMessageBox.Show(ErrorCode.DUPLICATE_KEY, MessageBoxIcon.Error);
                    txtTransNo.Focus();
                }
                else
                    PCSMessageBox.Show(ex.mCode, MessageBoxIcon.Error);
                try
                {
                    Logger.LogMessage(ex.CauseException, METHOD_NAME, Level.ERROR);
                }
                catch
                {
                    PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION);
                }
            }
            catch (Exception ex)
            {
                PCSMessageBox.Show(ErrorCode.OTHER_ERROR);
                try
                {
                    Logger.LogMessage(ex, METHOD_NAME, Level.ERROR);
                }
                catch
                {
                    PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION);
                }
            }
        }

        private void txtTransNo_Validating(object sender, CancelEventArgs e)
        {
            const string METHOD_NAME = THIS + ".txtTransNo_Validating()";
            try
            {
                if (txtTransNo.Modified && btnTransNo.Enabled)
                {
                    if (txtTransNo.Text.Trim().Equals(string.Empty))
                    {
                        ClearForm(true);
                        return;
                    }
                    else
                    {
                        DataRowView drvResult = FormControlComponents.OpenSearchForm(SO_ConfirmShipMasterTable.TABLE_NAME, SO_ConfirmShipMasterTable.CONFIRMSHIPNO_FLD, txtTransNo.Text.Trim(), null, false);
                        if (drvResult != null)
                        {
                            txtTransNo.Text = drvResult[SO_ConfirmShipMasterTable.CONFIRMSHIPNO_FLD].ToString();
                            txtTransNo.Tag = Convert.ToInt32(drvResult[SO_ConfirmShipMasterTable.CONFIRMSHIPMASTERID_FLD]);
                            LoadDataFromMaster(Convert.ToInt32(drvResult[SO_ConfirmShipMasterTable.CONFIRMSHIPMASTERID_FLD]));
                        }
                        else
                            e.Cancel = true;
                    }
                }
            }
            catch (PCSException ex)
            {
                PCSMessageBox.Show(ex.mCode, MessageBoxIcon.Error);
                try
                {
                    Logger.LogMessage(ex.CauseException, METHOD_NAME, Level.ERROR);
                }
                catch
                {
                    PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION);
                }
            }
            catch (Exception ex)
            {
                PCSMessageBox.Show(ErrorCode.OTHER_ERROR);
                try
                {
                    Logger.LogMessage(ex, METHOD_NAME, Level.ERROR);
                }
                catch
                {
                    PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION);
                }
            }
        }

        private void txtTransNo_KeyDown(object sender, KeyEventArgs e)
        {
            const string METHOD_NAME = THIS + ".txtTransNo_KeyDown()";
            try
            {
                if (e.KeyCode == Keys.F4)
                    btnTransNo_Click(null, null);
            }
            catch (PCSException ex)
            {
                PCSMessageBox.Show(ex.mCode, MessageBoxIcon.Error);
                try
                {
                    Logger.LogMessage(ex.CauseException, METHOD_NAME, Level.ERROR);
                }
                catch
                {
                    PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION);
                }
            }
            catch (Exception ex)
            {
                PCSMessageBox.Show(ErrorCode.OTHER_ERROR);
                try
                {
                    Logger.LogMessage(ex, METHOD_NAME, Level.ERROR);
                }
                catch
                {
                    PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION);
                }
            }
        }

        private void btnTransNo_Click(object sender, EventArgs e)
        {
            const string METHOD_NAME = THIS + ".btnTransNo_Click()";
            try
            {
                DataRowView drvResult = FormControlComponents.OpenSearchForm(SO_ConfirmShipMasterTable.TABLE_NAME, SO_ConfirmShipMasterTable.CONFIRMSHIPNO_FLD, txtTransNo.Text.Trim(), null, true);
                if (drvResult != null)
                {
                    txtTransNo.Text = drvResult[SO_ConfirmShipMasterTable.CONFIRMSHIPNO_FLD].ToString();
                    txtTransNo.Tag = Convert.ToInt32(drvResult[SO_ConfirmShipMasterTable.CONFIRMSHIPMASTERID_FLD]);
                    LoadDataFromMaster(Convert.ToInt32(drvResult[SO_ConfirmShipMasterTable.CONFIRMSHIPMASTERID_FLD]));
                }
                else
                    txtTransNo.Focus();
            }
            catch (PCSException ex)
            {
                PCSMessageBox.Show(ex.mCode, MessageBoxIcon.Error);
                try
                {
                    Logger.LogMessage(ex.CauseException, METHOD_NAME, Level.ERROR);
                }
                catch
                {
                    PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION);
                }
            }
            catch (Exception ex)
            {
                PCSMessageBox.Show(ErrorCode.OTHER_ERROR);
                try
                {
                    Logger.LogMessage(ex, METHOD_NAME, Level.ERROR);
                }
                catch
                {
                    PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION);
                }
            }
        }

        private void txtCommitNo_Validating(object sender, CancelEventArgs e)
        {
            const string METHOD_NAME = THIS + ".txtCommitNo_Validating()";
            try
            {
                if (txtCommitNo.Modified && btnCommitNo.Enabled)
                {
                    if (txtCommitNo.Text.Trim().Equals(string.Empty))
                    {
                        ClearForm(false);
                        return;
                    }
                    else
                    {
                        DataRowView drvResult = FormControlComponents.OpenSearchForm("v_CommitMasterToShipping", SO_CommitInventoryMasterTable.COMMITMENTNO_FLD, txtCommitNo.Text.Trim(), null, false);
                        if (drvResult != null)
                        {
                            txtCommitNo.Text = drvResult[SO_CommitInventoryMasterTable.COMMITMENTNO_FLD].ToString();
                            txtCommitNo.Tag = Convert.ToInt32(drvResult[SO_CommitInventoryMasterTable.COMMITINVENTORYMASTERID_FLD]);
                            FillCommitData(Convert.ToInt32(txtCommitNo.Tag));
                        }
                        else
                            e.Cancel = true;
                    }
                }
            }
            catch (PCSException ex)
            {
                PCSMessageBox.Show(ex.mCode, MessageBoxIcon.Error);
                try
                {
                    Logger.LogMessage(ex.CauseException, METHOD_NAME, Level.ERROR);
                }
                catch
                {
                    PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION);
                }
            }
            catch (Exception ex)
            {
                PCSMessageBox.Show(ErrorCode.OTHER_ERROR);
                try
                {
                    Logger.LogMessage(ex, METHOD_NAME, Level.ERROR);
                }
                catch
                {
                    PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION);
                }
            }
        }

        private void txtCommitNo_KeyDown(object sender, KeyEventArgs e)
        {
            const string METHOD_NAME = THIS + ".txtCommitNo_KeyDown()";
            try
            {
                if (e.KeyCode == Keys.F4)
                    btnCommitNo_Click(null, null);
            }
            catch (PCSException ex)
            {
                PCSMessageBox.Show(ex.mCode, MessageBoxIcon.Error);
                try
                {
                    Logger.LogMessage(ex.CauseException, METHOD_NAME, Level.ERROR);
                }
                catch
                {
                    PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION);
                }
            }
            catch (Exception ex)
            {
                PCSMessageBox.Show(ErrorCode.OTHER_ERROR);
                try
                {
                    Logger.LogMessage(ex, METHOD_NAME, Level.ERROR);
                }
                catch
                {
                    PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION);
                }
            }
        }

        private void btnCommitNo_Click(object sender, EventArgs e)
        {
            const string METHOD_NAME = THIS + ".btnCommitNo_Click()";
            try
            {
                DataRowView drvResult = FormControlComponents.OpenSearchForm("v_CommitMasterToShipping", SO_CommitInventoryMasterTable.COMMITMENTNO_FLD, txtCommitNo.Text.Trim(), null, true);
                if (drvResult != null)
                    FillCommitData(Convert.ToInt32(drvResult[SO_CommitInventoryMasterTable.COMMITINVENTORYMASTERID_FLD]));
                else
                    txtCommitNo.Focus();
            }
            catch (PCSException ex)
            {
                PCSMessageBox.Show(ex.mCode, MessageBoxIcon.Error);
                try
                {
                    Logger.LogMessage(ex.CauseException, METHOD_NAME, Level.ERROR);
                }
                catch
                {
                    PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION);
                }
            }
            catch (Exception ex)
            {
                PCSMessageBox.Show(ErrorCode.OTHER_ERROR);
                try
                {
                    Logger.LogMessage(ex, METHOD_NAME, Level.ERROR);
                }
                catch
                {
                    PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION);
                }
            }
        }
    }
}
